<?php

session_start();
include 'inc/db_connect.php';
include 'inc/db_op.php';
include 'inc/html_op.php';
include 'inc/form_op.php';

$page_title = "Login";
$debug = 0;

$user_id = $_SESSION['user_id'];

function get_login_form() {
  $html_str = "";
  $html_str .= '<form name="login" id="login" method="post">'.
               '口令：<input type="password" name="password" size=20></input>'.
               '<button type="submit" name="submit">登录</button>'.
               '&nbsp &nbsp <a href="get_pwd.php">获取口令</a></form>';
               return $html_str;
  return $html_str;
}

function get_content() {
  $html_str = "<p>";
  
  if(isset($_POST['logout'])) {
  $_SESSION = array();
  session_destroy();
  $html_str =  'Logged out.';
  } else {
    if(isset($_SESSION['logged'])) { //logged
      $html_str .= "<form method='POST'> ".$_SESSION['name']."<button type='submit' name='logout'>Logout</button></form>";
    } else { //not logged
      if(isset($_POST['submit']) && isset($_POST['password'])) { //submitted
        $password=$_POST['password'];
	    $sql = "select id, name from user_info where password like '$password' and (disabled = 0 or disabled is null)";
        $query = mysql_query("select id, name from user_info where password like '$password' and (disabled = 0 or disabled is null)");
        $row=mysql_num_rows($query);
        if(mysql_num_rows($query) > 0) {
          $row=mysql_fetch_array($query);
          $_SESSION['logged'] = true;
          $_SESSION['name'] = $row['name'];
          $_SESSION['user_id'] = $row['id'];

		  $sql = "select department_id from user_info where id = ".$_SESSION['user_id'];
          $_SESSION['department_id'] = db_get_one_value($sql);
          $sql = "select name from department where id = ".$_SESSION['department_id'];
          $_SESSION['department_name'] = db_get_one_value($sql);

          mysql_query("update user_info set latest_login = now() where id = ".$row['id']);
          if(isset($_SESSION['logged'])) $html_str .= 'Logged.';
          $html_str .= "<script>location.href='.'</script>";
        } else {
          $html_str .= '错误，请重试。<br/>';
          $html_str .= get_login_form();
        }
      } else {
        $html_str .= get_login_form();
      }
    }
  }
  $html_str .= "</p>";

  return $html_str;
}

$content = get_content();
$login_required = 0;
echo gen_onecol_page($page_title, $content, $debug, $login_required);

?>